<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户角色</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <el-row>
        <el-button type="primary">新增角色</el-button>
      </el-row>
      <!-- 表格展示 -->
      <el-table :data="roleList" border>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <!-- 通过三层for循环渲染数据 -->
          <template slot-scope="scope">
            <el-row
              :class="[i1===0?'':'rtop','rcenter']"
              v-for="(item1,i1) in scope.row.children"
              :key="item1.id"
            >
              <el-col :span="6">
                <el-tag closable @close="deleteRole(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="18">
                <el-row
                  :class="[i2===0?'':'rtop','rcenter']"
                  v-for="(item2,i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="8">
                    <el-tag
                      type="success"
                      closable
                      @close="deleteRole(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="16">
                    <el-tag
                      type="warning"
                      v-for="(item3,i3) in item2.children"
                      :key="item3.id"
                      closable
                      @close="deleteRole(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="setDialong(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限弹出框 -->
    <el-dialog title="分配权限" :visible.sync="dialogVisible" width="50%" @close="clearActiveKeys">
      <el-tree
        ref="roleRef"
        :data="roleTree"
        :props="defaultProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="activeKeys"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRight">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      //角色权限列表
      roleList: [],
      //树形角色权限列表
      roleTree: [],
      //弹出框
      dialogVisible: false,
      //默认展示的属性
      defaultProps: {
        //读取的子节点
        children: 'children',
        //展示的节点
        label: 'authName'
      },
      //默认选中的节点
      activeKeys: [],
      //点击分配权限的角色id
      roleId: ''
    };
  },
  created() {
    this.getRoleList();
  },
  methods: {
    //获取角色权限列表
    async getRoleList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) return this.$message.erroe("获取失败");
      this.roleList = res.data;
    },
    //删除角色指定权限
    deleteRole(role, rightId) {
      let _this = this;
      console.log(result);
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const { data: res } = await _this.$http.delete(
            `roles/${role.id}/rights/${rightId}`
          );
          if (res.meta.status !== 200) return _this.$message.error("删除失败");
          _this.$message.success("删除成功");
          //返回的data, 是当前角色下最新的权限数据
          role.children = res.data;
        })
        .catch(() => {
          _this.$message.info("已取消删除");
        });
    },
    //分配权限
    async setDialong(role) {
      this.dialogVisible = true;
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status !== 200)
        return this.$message.error("获取权限列表失败");
      this.roleTree = res.data;
      //调用递归 获取默认选中的节点
      this.getRights(role, this.activeKeys);
      //每次点击将该角色id进行保存
      this.roleId = role.id;
    },
    //递归获取该角色下的权限
    getRights(role, activeKeys) {
      //如果没有children属性证明是最后一个节点 直接放进数组
      if (!role.children) {
        this.activeKeys.push(role.id);
      } else {
        //循环调用递归
        role.children.forEach(r => {
          this.getRights(r, activeKeys);
        });
      }

      return activeKeys;
    },
    //每次关闭清空数组
    clearActiveKeys() {
      this.activeKeys = [];
    },
    //点击确定分配权限
    async allotRight() {
      //定义数组 通过组件引用拿到选中的权限
      const keyArr = [
        //得到选中的三级节点id
        ...this.$refs.roleRef.getCheckedKeys(),
        //获取到父节点的id
        ...this.$refs.roleRef.getHalfCheckedKeys()
      ];
      //发送请求
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, {
        rids: keyArr.join(",")
      });
      if (res.meta.status !== 200) {
        return this.$message.error("分配权限失败");
      }
      this.$message.success("分配权限成功");
      //重新加载
      this.getRoleList();
      //关闭对话框
      this.dialogVisible = false;
    }
  }
};
</script>
<style scoped>
.el-tag {
  margin: 10px;
}
.rtop {
  border-top: 1px solid #eee;
}
.rbot {
  border-bottom: 1px solid #eee;
}
.rcenter {
  display: flex;
  align-items: center;
}
</style>